var generateManager = {
    findTemplateUrl: '/generate/hzbgtemplate/findAll',
    findDataSourceUrl: '/generate/hzbgdatasource/findAll',
    findParamsUrl: '/generate/hzbgtemplateparam/findAll',
    findStructureUrl: '/generate/hzbgtemplatestructure/findTree',
    generateUrl: '/generate/generate/generateCode',
    init: function () {
        layui.use(['tree', 'util', 'layer', 'form'], function () {
            generateManager.refreshTemplate();
            generateManager.refreshDataSource();
            generateManager.refreshTree(null);
            generateManager.initListener();
            layui.form.on('submit(generateStart)', generateManager.startGenerate);
        });
    },

    /**
     * 初始化监听器
     */
    initListener: function () {
        layui.form.on('select(hbgtId)', function (data) {
            let value = data.value;
            generateManager.refreshTree(value);
            generateManager.refreshParam(value);
        });
    },

    /**
     * 刷新数据源
     */
    refreshDataSource: function () {
        hs_utils.post(generateManager.findDataSourceUrl, {}, function (data) {
            let data_ = data.data;
            if (data_) {
                let html = '<option value="">请先选择数据源</option>';
                for (let index in data_) {
                    let option = data_[index];
                    html += '<option value="' + option.hbgdsId + '">' + option.hbgdsName + '</option>';
                }
                $('#hbgdsId').html(html);
                layui.form.render('select', 'dataSourceForm');
            }
        })
    },

    /**
     * 刷新模板
     */
    refreshTemplate: function () {
        hs_utils.post(generateManager.findTemplateUrl, {}, function (data) {
            let data_ = data.data;
            if (data_) {
                let html = '<option value="">请先选择模板</option>';
                for (let index in data_) {
                    let option = data_[index];
                    html += '<option value="' + option.hbgtId + '">' + option.hbgtName + '</option>';
                }
                $('#hbgtId').html(html);
                layui.form.render('select', 'templateForm');
            }
        })
    },

    // 刷新树
    refreshTree: function (hbgtId) {
        hs_utils.post(generateManager.findStructureUrl, {hbgtId: hbgtId}, function (data) {
            if (data.success) {
                let tree = layui.tree,
                    layer = layui.layer,
                    util = layui.util;
                let rootData = [{
                    title: 'Root',
                    id: -1,
                    parentId: null,
                    attribute: null,
                    children: generateManager.treeConversion(data.data)
                }];
                tree.render({
                    elem: '#templateStructureTree',
                    data: rootData,
                    id: 'id',
                    showCheckbox: true,
                    customOperate: true,
                    edit: []
                });
            }
        })
    },

    // 树形数据转换
    treeConversion: function (data, nodeId) {
        let resultData = [];
        if (!data) {
            return resultData;
        }
        for (let index in data) {
            let node = data[index];
            let spread_ = false;
            if (nodeId && nodeId == node.id) {
                spread_ = true;
            }
            resultData.push({
                title: node.name,
                id: node.id,
                parentId: node.parentId,
                attribute: node.attribute,
                spread: spread_,
                children: generateManager.treeConversion(node.child, nodeId)
            });
        }
        return resultData;
    },

    // 获取节点与子节点的ID集合，使用,分隔
    getIds: function (node) {
        let ids = node.id;
        for (let index in node.children) {
            ids += "," + generateManager.getIds(node.children[index]);
        }
        return ids;
    },

    // 刷新参数
    refreshParam: function (hbgtId) {
        hs_utils.post(generateManager.findParamsUrl, {hbgtId: hbgtId}, function (data) {
            if (data.success) {
                let paramHtml = generateManager.getParamHtml(data.data);
                $('#paramsDiv').html(paramHtml);
            } else {
                layui.layer.msg(data.msg);
            }
        });
    },

    // 获取参数的表单代码
    getParamHtml: function (data) {
        let resultHtml = "";
        if (!data) {
            return resultHtml;
        }
        for (var index in data) {
            let param = data[index];
            if (index % 2 == 0) {
                resultHtml += "<div class=\"layui-form-item\">";
            }
            let required = param.required == 1 ? "required" : "";
            resultHtml += "<div class=\"layui-inline\">\n" +
                "   <label class=\"layui-form-label\">" + param.paramName + "</label>\n" +
                "   <div class=\"layui-input-inline\">\n" +
                "       <input type=\"text\" class=\"layui-input\" name=\"" + param.paramFlag + "\" " + required + " lay-verify=\"" + required + "\" placeholder=\"请输入" + param.paramName + "\"\n" +
                "       autocomplete=\"off\"\n>\n" +
                "   </div>\n" +
                "</div>";
            if ((index + 1) % 2 == 0 || index + 1 >= data.length) {
                // 如果下一个下标是3的整倍数或者已是最后一个下标，则添加行结束标志
                resultHtml += "</div>"
            }
        }
        return resultHtml;
    },

    startGenerate: function (data) {
        // 判断是否选择了数据源
        let hbgdsId = $('#hbgdsId').val();
        if (!hbgdsId) {
            layui.layer.msg("请先选择数据源");
            return false;
        }
        // 判断是否选择了模板
        let hbgtId = $('#hbgtId').val();
        if (!hbgtId) {
            layui.layer.msg("请先选择模板");
            return false;
        }
        let tableNames = data.field.generateTables.split(',');
        delete data.field.generateTables;
        let postData = {
            sourceId: hbgdsId,
            hbgtId: hbgtId,
            tableNames: tableNames,
            params: data.field
        }
        hs_utils.postDownload(generateManager.generateUrl, postData, null, null, true);
        return false;
    }
}
generateManager.init();